package com.sch.wanandroid.ui.main

import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.Switch
import android.widget.TextView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.MenuItemCompat
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.ViewModelProvider
import com.coder.zzq.smartshow.toast.SmartToast
import com.sch.wanandroid.R
import com.sch.wanandroid.base.BaseActivity
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.event.LoginEvent
import com.sch.wanandroid.event.LogoutEvent
import com.sch.wanandroid.ui.girls.GirlsActivity
import com.sch.wanandroid.ui.login.LoginActivity
import com.sch.wanandroid.ui.main.discover.DiscoverFragment
import com.sch.wanandroid.ui.main.home.HomeFragment
import com.sch.wanandroid.ui.main.squrare.SquareFragment
import com.sch.wanandroid.ui.main.tab.TabFragment
import com.sch.wanandroid.ui.my.share.MyShareActivity
import com.sch.wanandroid.ui.my.coin.CoinActivity
import com.sch.wanandroid.ui.my.collect.MyCollectActivity
import com.sch.wanandroid.ui.my.rank.RankActivity
import com.sch.wanandroid.ui.search.SearchActivity
import com.sch.wanandroid.ui.set.SetActivity
import com.sch.wanandroid.ui.web.WebActivity
import com.sch.wanandroid.util.AppManager
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.nav_header_main.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : BaseActivity() {
    private lateinit var mainViewModel: MainViewModel

    private val FRAGMENT_HOME = 0x01
    private val FRAGMENT_SQUARE = 0x02
    private val FRAGMENT_WECHAT = 0x03
    private val FRAGMENT_SYSTEM = 0x04
    private val FRAGMENT_PROJECT = 0x05

    private var mIndex = FRAGMENT_HOME

    private var mHomeFragment: HomeFragment? = null
    private var mSquareFragment: SquareFragment? = null
    private var mWeChatFragment: TabFragment? = null
    private var mDiscoverFragment: DiscoverFragment? = null
    private var mProjectFragment: TabFragment? = null

    /**
     * username TextView
     */
    private var nav_username: TextView? = null

    /**
     * user_grade TextView
     */
    private var nav_user_level: TextView? = null

    /**
     * user_rank TextView
     */
    private var nav_user_rank: TextView? = null

    /**
     * score TextView
     */
    private var nav_score: TextView? = null

    /**
     * rank ImageView
     */
    private var nav_rank: ImageView? = null

    private var switchNightMode: Switch? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("lastIndex", mIndex)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun init(savedInstanceState: Bundle?) {
        val temp = savedInstanceState?.getInt("lastIndex")
        temp?.let {
            mIndex = it
        }
        mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        toolbar.run {
            title = getString(R.string.app_name)
            setSupportActionBar(this)
        }
        drawer_layout.run {
            val toggle = ActionBarDrawerToggle(
                this@MainActivity,
                this, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close
            )
            addDrawerListener(toggle)
            toggle.syncState()
        }
        initNavView()
        initBottom()
        showFragment(mIndex)
        mainViewModel.userInfo.observe(this) {
            nav_username?.text = mainViewModel.userInfo.value!!.username
            nav_user_level?.text = mainViewModel.userInfo.value!!.level
            nav_user_rank?.text = mainViewModel.userInfo.value!!.rank
            nav_score?.text = mainViewModel.userInfo.value!!.coinCount
        }
        fab.setOnClickListener {
            when (mIndex) {
                FRAGMENT_HOME -> {
                    mHomeFragment?.scrollToTop()
                }
                FRAGMENT_SQUARE -> {
                    mSquareFragment?.scrollToTop()
                }
                FRAGMENT_SYSTEM -> {
                    mDiscoverFragment?.scrollToTop()
                }
                FRAGMENT_PROJECT -> {
                    mProjectFragment?.scrollToTop()
                }
                FRAGMENT_WECHAT -> {
                    mWeChatFragment?.scrollToTop()
                }
            }
            fab.visibility = View.INVISIBLE
        }

    }

    private fun initNavView() {
        nav_view.run {
            nav_username = getHeaderView(0).findViewById(R.id.tv_username)
            nav_user_level = getHeaderView(0).findViewById(R.id.tv_user_level)
            nav_user_rank = getHeaderView(0).findViewById(R.id.tv_user_rank)
            nav_rank = getHeaderView(0).findViewById(R.id.iv_rank)
            nav_score =
                MenuItemCompat.getActionView(nav_view.menu.findItem(R.id.nav_score)) as TextView
            nav_score?.gravity = Gravity.CENTER_VERTICAL
            switchNightMode = MenuItemCompat.getActionView(nav_view.menu.findItem(R.id.nav_night)) as Switch
            switchNightMode?.isEnabled = false
            switchNightMode?.isChecked = MMKV.defaultMMKV().decodeBool(Constants.NIGHT_MODEL, false)
            nav_view.setNavigationItemSelectedListener {
                when (it.itemId) {
                    R.id.nav_score -> {
                        intent(Bundle().apply {
                            putString(
                                Constants.MY_COIN,
                                mainViewModel.userInfo.value!!.coinCount
                            )
                        }, CoinActivity::class.java, true)
                    }
                    R.id.nav_collect -> {
                        intent(MyCollectActivity::class.java, true)
                    }
                    R.id.nav_share -> {
                        intent(MyShareActivity::class.java, true)
                    }
                    R.id.nav_girls -> {
                        intent(GirlsActivity::class.java, false)
                    }
                    R.id.nav_website -> {
                        intent(Bundle().apply {
                            putString(Constants.WEB_URL, getString(R.string.WanAndroidUrl))
                            putString(Constants.WEB_TITLE, "WanAndroid")
                        }, WebActivity::class.java, false)
                    }
                    R.id.nav_night -> {
                        val isNightModel: Boolean =
                            MMKV.defaultMMKV().decodeBool(Constants.NIGHT_MODEL, false)
                        if (isNightModel) {
                            switchNightMode?.isChecked = false
                            MMKV.defaultMMKV().encode(Constants.NIGHT_MODEL, false)
                            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                        } else {
                            switchNightMode?.isChecked = true
                            MMKV.defaultMMKV().encode(Constants.NIGHT_MODEL, true)
                            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                        }
                        window.setWindowAnimations(R.style.NightModelAnim)
                        recreate()
                    }

                    R.id.nav_set -> {
                        intent(SetActivity::class.java, false)
                    }
                }
                true
            }
        }
        nav_username?.setOnClickListener {
            if (!AppManager.isLogin()) {
                intent(LoginActivity::class.java, false)
            }
        }
        nav_rank?.setOnClickListener {
            intent(Bundle().apply {
                putString(Constants.MY_COIN, mainViewModel.userInfo.value!!.coinCount)
                putString(Constants.MY_RANK, mainViewModel.userInfo.value!!.rank)
            }, RankActivity::class.java, true)
        }
    }


    /**
     * 初始化下方切换控件 BottomNavigationView
     */
    private fun initBottom() {
        btmNavigation.run {
            setOnNavigationItemSelectedListener {
                when (it.itemId) {
                    R.id.menu_home -> showFragment(FRAGMENT_HOME)
                    R.id.menu_project -> showFragment(FRAGMENT_PROJECT)
                    R.id.menu_wxchart -> showFragment(FRAGMENT_WECHAT)
                    R.id.menu_square -> showFragment(FRAGMENT_SQUARE)
                    R.id.menu_system -> showFragment(FRAGMENT_SYSTEM)
                }
                true
            }
        }
    }

    private fun showFragment(position: Int) {
        Log.e("test", "showFragment:$position")
        val transaction = supportFragmentManager.beginTransaction()
        hideFragments(transaction)
        mIndex = position
        when (mIndex) {
            FRAGMENT_HOME -> {
                toolbar.title = getString(R.string.app_name)
                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.getInstance()
                    Log.e("test", "add mHomeFragment")
                    transaction.add(R.id.container, mHomeFragment!!, "home")
                } else {
                    transaction.show(mHomeFragment!!)
                }
            }
            FRAGMENT_SQUARE -> {
                toolbar.title = getString(R.string.tab_square)
                if (mSquareFragment == null) {
                    mSquareFragment = SquareFragment.getInstance()
                    transaction.add(R.id.container, mSquareFragment!!, "square")
                } else {
                    transaction.show(mSquareFragment!!)
                }
            }
            FRAGMENT_SYSTEM -> {
                toolbar.title = getString(R.string.tab_system)
                if (mDiscoverFragment == null) {
                    mDiscoverFragment = DiscoverFragment.getInstance()
                    transaction.add(R.id.container, mDiscoverFragment!!, "system")
                } else {
                    transaction.show(mDiscoverFragment!!)
                }
            }
            FRAGMENT_PROJECT -> {
                toolbar.title = getString(R.string.tab_project)
                if (mProjectFragment == null) {
                    mProjectFragment = TabFragment.newInstance(Constants.PROJECT_TYPE)
                    transaction.add(R.id.container, mProjectFragment!!, "project")
                } else {
                    transaction.show(mProjectFragment!!)
                }
            }
            FRAGMENT_WECHAT -> {
                toolbar.title = getString(R.string.tab_wx_chart)
                if (mWeChatFragment == null) {
                    mWeChatFragment = TabFragment.newInstance(Constants.WX_TYPE)
                    transaction.add(R.id.container, mWeChatFragment!!, "wechat")
                } else {
                    transaction.show(mWeChatFragment!!)
                }
            }
        }
        transaction.commit()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        if (mIndex != FRAGMENT_SQUARE) {
            menuInflater.inflate(R.menu.menu_activity_main, menu)
        }
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_search -> {
                intent(SearchActivity::class.java, false)
                //瞬间开启activity，无动画
                overridePendingTransition(R.anim.anim_no, R.anim.anim_no)
            }

        }

        return super.onOptionsItemSelected(item)
    }


    /**
     * 隐藏所有的Fragment
     */
    private fun hideFragments(transaction: FragmentTransaction) {
        mHomeFragment?.let { transaction.hide(it) }
        mSquareFragment?.let { transaction.hide(it) }
        mDiscoverFragment?.let { transaction.hide(it) }
        mProjectFragment?.let { transaction.hide(it) }
        mWeChatFragment?.let { transaction.hide(it) }
    }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        mHomeFragment = null
        mSquareFragment = null
        mDiscoverFragment = null
        mProjectFragment = null
        mWeChatFragment = null
        super.onDestroy()
    }

    override fun recreate() {
        try {
            val fragmentTransaction = supportFragmentManager.beginTransaction()
            if (mHomeFragment != null) {
                fragmentTransaction.remove(mHomeFragment!!)
            }
            if (mSquareFragment != null) {
                fragmentTransaction.remove(mSquareFragment!!)
            }
            if (mDiscoverFragment != null) {
                fragmentTransaction.remove(mDiscoverFragment!!)
            }
            if (mProjectFragment != null) {
                fragmentTransaction.remove(mProjectFragment!!)
            }
            if (mWeChatFragment != null) {
                fragmentTransaction.remove(mWeChatFragment!!)
            }
            fragmentTransaction.commitNowAllowingStateLoss()
            super.recreate()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 登陆消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun loginEvent(loginEvent: LoginEvent) {
        mainViewModel.getUserCoinInfo()
    }

    /**
     * 登陆消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun logoutEvent(logout: LogoutEvent) {
        mainViewModel.clearUserInfo()
    }


    var lastTime: Long = 0
    override fun onBackPressed() {
        if (System.currentTimeMillis() - this.lastTime > 2000L) {
            SmartToast.show("再按一次退出程序")
            this.lastTime = System.currentTimeMillis()
            return
        } else {
            super.onBackPressed()
        }
    }
}
